package com.cxh.rmsq.ui.activity.self

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.CheckBox
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.databinding.ActivityPubExchangeBinding
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.ui.BaseActivity
import com.cxh.rmsq.ui.adapter.self.CampClockImageAdapter
import com.cxh.rmsq.ui.adapter.self.CampClockImageNewAdapter
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyUtils
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.dialog.CluePopup
import com.cxh.rmsq.utils.log.SLog
import com.cxh.rmsq.utils.recyclerview.FullyGridLayoutManager
import com.cxh.rmsq.utils.recyclerview.GridSpacingItemDecoration
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import com.lxj.xpopup.XPopup
import java.util.Arrays


/**
 * 发布兑换
 */
class PubExchangeActivity : BaseActivity() {
    private lateinit var binding: ActivityPubExchangeBinding

    private var locationId = ""
    private var name = ""
    private var checkinPlatform = 2 //1抖音2小红书
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }
    private val proViewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }

    // 定义颜色状态列表
    var states = arrayOf(intArrayOf(android.R.attr.state_checked), intArrayOf())

    var colors = intArrayOf(
        Color.parseColor("#FBD87B"),  // 选中颜色
        Color.parseColor("#E0D5B0") // 未选中颜色
    )

    private var imageAdapter: CampClockImageNewAdapter? = null
    private val imagesMediaList = java.util.ArrayList<LocalMedia>()
    private var imageSelectMax = 5
    private var files = ""

    @SuppressLint("RestrictedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPubExchangeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.clToolbar.setPadding(0, 0, 0, 0)
//        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        locationId = intent.getStringExtra("locationId").toString()
        name = intent.getStringExtra("name").toString()

        val colorStateList = ColorStateList(states, colors)
        // 设置颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            binding.cbDou.setButtonTintList(colorStateList)
            binding.cbRed.setButtonTintList(colorStateList)
        } else {
            // 使用 AppCompatCheckBox 兼容旧版本
            val compatCheckBox = binding.cbDou as AppCompatCheckBox
            compatCheckBox.supportButtonTintList = colorStateList
            val compatCheckBox2 = binding.cbRed as AppCompatCheckBox
            compatCheckBox2.supportButtonTintList = colorStateList
        }


        val manager = FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
        binding.rlvCampClockImages.setLayoutManager(manager)
        val itemAnimator: RecyclerView.ItemAnimator = binding.rlvCampClockImages.getItemAnimator()!!
        if (itemAnimator != null) {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations =
                false
        }
        binding.rlvCampClockImages.addItemDecoration(
            GridSpacingItemDecoration(4, ConvertUtils.dp2px(5f), false)
        )
        imageAdapter = CampClockImageNewAdapter(this, imagesMediaList)
        binding.rlvCampClockImages.setAdapter(imageAdapter)
        imageAdapter!!.setOnItemClickListener(object :
            CampClockImageNewAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                // 预览图片、视频、音频
                PictureSelector.create(this@PubExchangeActivity)
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .isPreviewFullScreenMode(true)
                    .isPreviewZoomEffect(true, binding.rlvCampClockImages)
                    .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                        override fun onPreviewDelete(position: Int) {
                            if (imagesMediaList.size > position) {
                                imagesMediaList.removeAt(position)
                                imageAdapter!!.notifyItemRemoved(position)
                            }
                            files = ""
                            if (imagesMediaList.size > 0) {
                                for (j in 0 until imagesMediaList.size) {
                                    proViewModel.updateSinglePic(imagesMediaList.get(j).realPath) {
                                        runOnUiThread {
                                            if (files == "") {
                                                files = it.data
                                            } else {
                                                files = files + "," + it.data
                                            }

                                            Log.e("imgpath", files)
                                        }
                                    }

                                }
                            }
                        }

                        override fun onLongPressDownload(
                            context: Context,
                            media: LocalMedia
                        ): Boolean {
                            return true
                        }
                    })
                    .startActivityPreview(position, true, imagesMediaList)
            }

            override fun openPicture() {
                selectPicture()
            }
        })

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.llSubmit.setOnClickListener {
            if (isFastClick) {
                return@setOnClickListener
            }
            if (!binding.cbDou.isChecked && !binding.cbRed.isChecked) {
                ToastUtils.showToast("请选择发布平台")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(files)) {
                ToastUtils.showToast("请上传动态图片")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding.setLink.text.toString().trim())) {
                ToastUtils.showToast("请填写动态链接")
                return@setOnClickListener
            }
            if (!MyUtils.isWechatAccount(binding.setLink.text.toString().trim())){
                binding.setLink.setText("")
                ToastUtils.showToast("请输入正确的链接")
                return@setOnClickListener
            }
            val paramsMap = HashMap<String, Any>()
            paramsMap["locationId"] = locationId
            paramsMap["progressId"] = intent.getStringExtra("progressId").toString()
            paramsMap["checkinPlatform"] = checkinPlatform
            paramsMap["imgUrl"] = files
            paramsMap["linkUrl"] = binding.setLink.text.toString().trim()
            viewModel.createExchange(paramsMap) {
                if (it.code == 200) {
                    XPopup.Builder(this)
                        .dismissOnTouchOutside(false)
                        .dismissOnBackPressed(false)
                        .asCustom(
                            CluePopup(this,
                                2,
                                name,
                                object : CluePopup.onClick {
                                    override fun click(s: String, s1: String) {
                                        finish()
                                    }
                                })
                        )
                        .show()
                } else {
                    ToastUtils.showToast(it.msg.toString())
                    finish()
                }
            }
        }
    }

fun onCheckboxClicked(view: View) {
    // 这是View.OnClickListener的一个简便写法，它会传递触发事件的视图对象。
    val checked = (view as CheckBox).isChecked
    when (view.getId()) {
        R.id.cb_dou -> {
            checkinPlatform = 1
            binding.cbDou.isChecked = true
            binding.cbRed.isChecked = false
        }

        R.id.cb_red -> {
            checkinPlatform = 2
            binding.cbDou.isChecked = false
            binding.cbRed.isChecked = true
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == RESULT_OK) {
        when (requestCode) {

            PictureConfig.CHOOSE_REQUEST -> {
                val selectList =
                    PictureSelector.obtainSelectorList(data)
                val isMaxSize = selectList.size == imageSelectMax
                val oldSize = imagesMediaList.size
                imageAdapter!!.notifyItemRangeRemoved(
                    0,
                    if (isMaxSize) oldSize + 1 else oldSize
                )

                imagesMediaList.clear()
                imagesMediaList.addAll(selectList)
                imageAdapter!!.notifyItemRangeInserted(0, selectList.size)

//                    for (media in result) {
                files = ""
                showLoadingDialog("上传中")
                for (j in 0 until imagesMediaList.size) {
                    proViewModel.updateSinglePic(imagesMediaList.get(j).realPath) {
                        runOnUiThread {
                            if (files == "") {
                                files = it.data
                            } else {
                                files = files + "," + it.data
                            }

                            Log.e("imgpath", files)
                            dismissLoadingDialog()
                        }
                    }
                }
            }

            else -> {}
        }
    }
}


private fun selectPicture() {
    val pictureSelector = PictureSelector.create(this)
    //        PictureSelector.create(this)
    var pictureSelectionModel: PictureSelectionModel? = null
    pictureSelectionModel = pictureSelector.openGallery(SelectMimeType.ofImage())

    pictureSelectionModel!!.setImageEngine(GlideEngine.createGlideEngine())
        .setMaxSelectNum(imageSelectMax)
        .isGif(true)
        .isMaxSelectEnabledMask(true)
        .isOriginalControl(true)
        .setSelectedData(imagesMediaList)
        .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
            override fun requestPermission(
                fragment: Fragment,
                permissionArray: Array<String>,
                call: OnRequestPermissionListener
            ) {
                val permissionInfoDialog = Dialog(fragment.requireActivity())
                //应用上架要求添加权限使用说明
                var permissionInfoTitle = ""
                var permissionInfoContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionInfoTitle =
                        resources.getString(R.string.permission_info_title_storage)
                    permissionInfoContent =
                        resources.getString(R.string.permission_info_content_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionInfoTitle =
                        resources.getString(R.string.permission_info_title_camera)
                    permissionInfoContent =
                        resources.getString(R.string.permission_info_content_camera)
                }
                if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                        permissionInfoContent
                    )
                ) {
                    CustomPermissionUtil.showPermissionInfo(
                        fragment.activity,
                        permissionInfoDialog,
                        permissionInfoTitle,
                        permissionInfoContent
                    )
                }

                //此处使用图片选择框架的权限申请
                PermissionChecker.getInstance().requestPermissions(
                    fragment,
                    permissionArray,
                    object : PermissionResultCallback {
                        override fun onGranted() {
                            permissionInfoDialog.dismiss()
                            call.onCall(permissionArray, true)
                        }

                        override fun onDenied() {
                            permissionInfoDialog.dismiss()
                            call.onCall(permissionArray, false)
                        }
                    })
            }

            override fun hasPermissions(
                fragment: Fragment,
                permissionArray: Array<String>
            ): Boolean {
                return PermissionChecker.isCheckSelfPermission(
                    fragment.context,
                    permissionArray
                )
            }
        })
        .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
            var permissionSetContent = ""
            if (Arrays.equals(
                    permissionArray,
                    PermissionConfig.getReadPermissionArray(
                        fragment.context,
                        SelectMimeType.ofImage()
                    )
                )
            ) {
                permissionSetContent = resources.getString(R.string.permission_set_storage)
            } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                permissionSetContent = resources.getString(R.string.permission_set_camera)
            }
            if (!TextUtils.isEmpty(permissionSetContent)) {
                CustomPermissionUtil.showPermissionSet(
                    fragment.activity,
                    permissionSetContent,
                    ArrayList(Arrays.asList(*permissionArray))
                ) { call.onCall(true) }
            }
        }
        .forResult(PictureConfig.CHOOSE_REQUEST)
}


}